<?php

/**
 * IndexController - The default controller class
 * 
 * @author
 * @version 
 */

require_once 'Zend/Controller/Action.php';

class Administrator_MatchController extends Zend_Controller_Action 
{
	

	
	public function init(){
		
		$member=new CMember();
		
		if(!$member->isUser($this->_request->getModuleName(),$this->_request->getControllerName())){
			
			$this->_redirect(MY_URL.'/administrator-auth-login');
			
		}
		
		
//		$memberArray = $member->getUserDetails(array('uid' => $_COOKIE[COOKIE_PRE.'uid']));
//    	if($_COOKIE[COOKIE_PRE.'uid']=='1'){
//				
//		} else {
//        	$strarray = explode(",", $memberArray[0]['menuflag']);
//        	
//        	if (!in_array('16', $strarray)) {
//        		exit('no priviage');
//        	}
//		}
		
	}
	
	public function preDispatch()
	{
		$this->getHelper ('layout')->setLayout('framelayout');
		$this->view->addHelperPath(MY_ROOT.'/vhelpers');
		Zend_Controller_Action_HelperBroker::addPath(MY_ROOT.'/chelpers');
	}

	public function indexAction()
	{
        $page = $this->_request->getParam("page", 1);
        $state = $this->_request->getParam("state");
        $matchinfo = new CMatchinfo();
        $matchinfo->refreshStatus();
        $fieldArray = null;
        if ($state != '') {
            $fieldArray['MatchStatus'] = $state;
        }
        $matchCounts = $matchinfo->getCounts($fieldArray);
        Zend_Loader::loadClass("CFilter");
        $pageArray = CFilter::filterPage($page, $matchCounts, 10);
        $matchArray = $matchinfo->getAll($pageArray['from'], 10, $fieldArray);
        Zend_Loader::loadClass("CPage");
        $pageString = CPage::divPages($pageArray ['pageNumber'], $pageArray ['page'], ROOT_PATH . "/administrator-match-index?state=$state"); //生成分页字符串
        $this->view->assign("pageString", $pageString);
        $this->view->assign("pageArray", $pageArray);
        $this->view->assign('matchArray', $matchArray);
        $this->view->assign('state', $state);
	}

	public function addAction()
	{
		$param = array();
    	$param['MatchTime'] 	= strtotime(trim($this->_getParam('MatchTime','')));
    	$param['TeamA'] 		= $this->_getParam('TeamA','');
    	$param['TeamARate'] 	= $this->_getParam('TeamARate','');
    	$param['TeamAScore'] 	= $this->_getParam('TeamAScore','');
    	$param['TeamB'] 		= $this->_getParam('TeamB','');
    	$param['TeamBRate'] 	= $this->_getParam('TeamBRate','');
    	$param['TeamBScore'] 	= $this->_getParam('TeamBScore','');
    	$param['MatchStatus'] 	= $this->_getParam('MatchStatus','');
    	$param['TeamTypeA'] 	= $this->_getParam('TeamTypeA','');
    	$param['TeamTypeB'] 	= $this->_getParam('TeamTypeB','');
    	$param['TeamALogo'] 	= $this->_getParam('TeamALogo','');
    	$param['TeamBLogo'] 	= $this->_getParam('TeamBLogo','');
    	$param['MatchLogo'] 	= $this->_getParam('MatchLogo','');
    	$param['errormsg'] 		= '';
    	if($this->getRequest()->isPost()) {
    		try{
		    	if($param['MatchTime'] == '' || $param['TeamA'] == '' || $param['TeamB'] == '' || $param['TeamARate'] == '' || $param['TeamARate'] == '' || $param['TeamALogo'] == '' || $param['TeamBLogo'] == '' || $param['MatchLogo'] == '') {
		    		
		    		throw new Exception('带*号参数必填!');
		    	}
		    	$matchinfo = new CMatchinfo();
    			$matchinfo->insertMatch($param);
    		}catch (Exception $e) {
    			$param['errormsg'] = $e->getMessage();
    		}
    		if($param['errormsg'] == '')
    			$this->view->showMsg("添加成功!",'administrator-match-index');
    	}
    	$this->view->param = $param;
	}
	
	public function editAction()
	{
		$matchinfo = new CMatchinfo();
		$id = (int)$this->_getParam('id','');
		if($id > 0 && !$this->getRequest()->isPost()) {
			$param = $matchinfo->GetMatch($id);
			$param['TeamTypeA'] = $this->getTeamType($param['TeamA']);
			$param['TeamTypeB'] = $this->getTeamType($param['TeamB']);
		} elseif($this->getRequest()->isGet()) {
			$this->view->showMsg("错误的参数!",'administrator-match-index');
		}
    	$param['errormsg'] = '';
    	if($this->getRequest()->isPost()) {
	    	$param['MatchTime'] 	= strtotime(trim($this->_getParam('MatchTime','')));
	    	$param['TeamA'] 		= $this->_getParam('TeamA','');
	    	$param['TeamARate'] 	= $this->_getParam('TeamARate','');
	    	$param['TeamARateID'] 	= $this->_getParam('TeamARateID','');
	    	$param['TeamAScore'] 	= $this->_getParam('TeamAScore','');
	    	$param['TeamB'] 		= $this->_getParam('TeamB','');
	    	$param['TeamBRate'] 	= $this->_getParam('TeamBRate','');
	    	$param['TeamBRateID'] 	= $this->_getParam('TeamBRateID','');
	    	$param['TeamBScore'] 	= $this->_getParam('TeamBScore','');
	    	$param['MatchStatus'] 	= $this->_getParam('MatchStatus','');
	    	$param['MatchID'] 		= $this->_getParam('MatchID','');
	    	$param['TeamTypeA'] 	= $this->_getParam('TeamTypeA','');
    		$param['TeamTypeB'] 	= $this->_getParam('TeamTypeB','');
    		$param['TeamALogo'] 	= $this->_getParam('TeamALogo','');
    		$param['TeamBLogo'] 	= $this->_getParam('TeamBLogo','');
    		$param['MatchLogo'] 	= $this->_getParam('MatchLogo','');
    		try{
    			if($param['MatchTime'] == '' || $param['TeamA'] == '' || $param['TeamB'] == '' || $param['TeamARate'] == '' || $param['TeamARate'] == '' || $param['TeamALogo'] == '' || $param['TeamBLogo'] == '' || $param['MatchLogo'] == '') {
		    		throw new Exception('带*号参数必填!');
		    	}
    			$matchinfo->updateMatchAdmin($param);
    		}catch (Exception $e) {
    			$param['errormsg'] = $e->getMessage();
    		}
    		if($param['errormsg'] == '')
    			$this->view->showMsg("编辑成功!",'administrator-match-index');
    	}
    	$this->view->param = $param;
	}
	
	public function deleteAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		$id=$this->_request->getParam('id',0);
		if($id > 0) {
			$matchinfo = new CMatchinfo();
			$result = $matchinfo->delete($id);
			if($result > 0) {
				$this->view->showMsg("删除成功!",'administrator-match-index');
			} else {
				$this->view->showMsg("删除失败!",'administrator-match-index');
			}
		} else {
			$this->view->showMsg("删除失败,参数错误!",'administrator-match-index');
		}
	}
	
	public function detailAction()
	{
		$mid = (int)$this->_getParam('id','');
		if($mid > 0) {
			$matchinfo = new CMatchinfo();
			$param = $matchinfo->GetMatchDetail($mid);
			
			if($param['ChipInA'] == 0 || $param['ChipInA'] == '') {
				$param['ChipInARate'] = '0%';
			} else {
				$param['ChipInARate'] = round($param['ChipInA']/$param['ChipInTotal']*100) . '%';
			}
			if($param['ChipInB'] == 0 || $param['ChipInB'] == '') {
				$param['ChipInBRate'] = '0%';
			} else {
				$param['ChipInBRate'] = round($param['ChipInB']/$param['ChipInTotal']*100) . '%';
			}
			
			//投注信息
			$page = $this->_request->getParam("page", 1);
	        $chipin = new CChipin();
	        $fieldArray['MatchID'] = $param['MatchID'];
	        $chipinCounts = $chipin->getCounts($fieldArray);
	        Zend_Loader::loadClass("CFilter");
	        $pageArray = CFilter::filterPage($page, $chipinCounts, 10);
	        $chipinArray = $chipin->getAll($pageArray['from'], 10, $fieldArray);
	        Zend_Loader::loadClass("CPage");
	        $pageString = CPage::divPages($pageArray ['pageNumber'], $pageArray ['page'], ROOT_PATH . "/administrator-match-detail?id={$param['MatchID']}"); //生成分页字符串
	        $this->view->assign("pageString", $pageString);
	        $this->view->assign('chipinArray', $chipinArray);
	        $this->view->assign('pageArray', $pageArray);
		} else {
			$this->view->showMsg("错误的参数!",'administrator-match-index');
		}
    	$this->view->param = $param;
	}
	
	public function nationalAction()
	{
		$page = $this->_request->getParam("page", 1);
		$pid = 93;
		$fenlei = new CFenlei('product');
		
        $fenleiCounts = $fenlei->getAllFlCountsByPid($pid);
        Zend_Loader::loadClass("CFilter");
        $pageArray = CFilter::filterPage($page, $fenleiCounts, 10);
        $fenleiArray = $fenlei->getAllFenleiByPid($pageArray['from'], 10, $pid);
        Zend_Loader::loadClass("CPage");
        $pageString = CPage::divPages($pageArray ['pageNumber'], $pageArray ['page'], ROOT_PATH . "/administrator-match-national"); //生成分页字符串
        $this->view->assign("pageString", $pageString);
        $this->view->assign("pageArray", $pageArray);
        $this->view->assign('fenleiArray', $fenleiArray);
	}
	
	public function clubAction()
	{
		$page = $this->_request->getParam("page", 1);
		$pid = 92;
		$fenlei = new CFenlei('product');
		
        $fenleiCounts = $fenlei->getAllFlCountsByPid($pid);
        Zend_Loader::loadClass("CFilter");
        $pageArray = CFilter::filterPage($page, $fenleiCounts, 10);
        $fenleiArray = $fenlei->getAllFenleiByPid($pageArray['from'], 10, $pid);
        Zend_Loader::loadClass("CPage");
        $pageString = CPage::divPages($pageArray ['pageNumber'], $pageArray ['page'], ROOT_PATH . "/administrator-match-club"); //生成分页字符串
        $this->view->assign("pageString", $pageString);
        $this->view->assign("pageArray", $pageArray);
        $this->view->assign('fenleiArray', $fenleiArray);
	}
	
	public function getteamsajaxAction()
	{
		$this->_helper->viewRenderer->setNoRender();

        $this->getHelper ('layout')->disableLayout ();

        $type=$this->_request->getParam('type','');

        $product=new CFenlei('product');
        
        if($type == '')
        	die('');
        switch ($type) {
        	case 'club':
        		$pid = 92;
        		break;
        	case 'national':
        		$pid = 93;
        		break;
        }

        $fenleiArray=$product->getFenleiByPid($pid);

        echo json_encode($fenleiArray);
	}
	
	public function getTeamType($tid)
	{
		$cfenlei = new CFenlei('product');
		$data = $cfenlei->getoneFenlei($tid);
		switch ($data[0]['pid']) {
			case 92:
				$return_str = 'club';
				break;
			case 93:
				$return_str = 'national';
				break;
		}
		return $return_str;
	}
	
	public function grantprizeAction()
	{
		$this->_helper->viewRenderer->setNoRender();
        $this->getHelper ('layout')->disableLayout ();
		$id = (int)$this->_getParam('id',0);
		$sendmail = $this->_getParam('sendmail', 0);
		if($id > 0){
			$matchinfo = new CMatchinfo();
			$error = '';
			try{
				$matchinfo->GrantPrize($id);
			}catch (Exception $e) {
    			$this->view->showMsg("奖励发放失败,error:".$e->getMessage(),'administrator-match-index');
    		}
    		if ($error == '') {
    			if ($sendmail == 1) {
    				$this->view->showMsg("奖励发放成功!即将自动跳转发送邮件给参与用户",'administrator-match-sendmail?id=' . $id);
    				return;
    			} else {
    				$this->view->showMsg("奖励发放成功!",'administrator-match-index');
    				return;
    			}
    		}
		} else {
			$this->view->showMsg("错误的参数!",'administrator-match-index');
		}
	}
	
	public function sendmailAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$matchId = intval($this->getRequest()->getParam('id'));
		$chipin = new CChipin();
		$sendArr = $chipin->sendMailValue($matchId);
		$matchInfo = new CMatchinfo();
		$mailer = new CMail();
		$matchScore = new CScore();
		ignore_user_abort();
		foreach ($sendArr as $v) {
			$time = date('Y-m-d H:i:s', $v['MatchTime']);
			$nickName = $v['nick_name'];
			$email = $v['email'];
			$teamA = $matchInfo->getTeam($v['TeamA']);
			$teamB = $matchInfo->getTeam($v['TeamB']);
			$teamAname = '';
			$teamBname = '';			
			if (!empty($teamA)) {
				$teamAname = $teamA['en_flname'];				
			}
			if (!empty($teamB)) {
				$teamBname = $teamB['en_flname'];
			}
			$team = $teamAname . ' VS ' . $teamBname;
			if ($v['GetScore'] == 0) {
				$isWin = 0;
				$score = $v['ChipInScore'];				
			} else {
				$isWin = 1;
				$score = $v['GetScore'];
			}
			$dollar = $matchScore->score2dollar($score);			
			$mailer->sendMatchMail($email, $nickName, $team, $time, $dollar, $isWin);
			sleep(2);
		}		
		$this->view->showMsg("奖励发放成功!",'administrator-match-index');
	}
	
	public function clubmembersAction()
	{
		$member = new CMember();
		//getUserCounts
		//getAllUsers
	}
    
    //图片处理函数
    public function uploadimgAction(){

    	header("Content-type: text/html; charset=utf-8");

    	$this->getHelper ('layout')->disableLayout ();

    	$upload=new CUpload();

    	$path=new CPath();

    	$thisPath=$path->getPathFromType('temp');

    	$imageArray=$upload->uploadFile($thisPath,null,null,'500000');

    	$isSuccess=false;

    	if(is_array($imageArray)){

    		$isSuccess=true;

	    	$imgUrl=$path->toDbPath('temp',$imageArray[0]);

	    	$this->view->assign('imgUrl',$imgUrl);

    	}else{

    		$error=$imageArray;

    		$this->view->assign('error',$error);

    	}

    	$this->view->assign('isSuccess',$isSuccess);

    }
    
    public function mailAction()
    {
    	$config = new CConfiguration();
    	
    	if ($this->getRequest()->isPost()) {
    		$configArray = $this->_request->getParams();
    		foreach ($configArray as $key => $value) {
				$config->editConfiguration($key,array('data'=>$value));
			}
			$this->getHelper('viewRenderer')->setNoRender();
			$this->view->showMsg('更新成功!');
    	}
    	
		$array = $config->getAllConfigurations();
		$configArray = array();
		foreach ($array as $value){
			$configArray[$value['name']] = $value['data'];
		}
		$this->view->assign('configArray',$configArray);
		require_once (MY_ROOT."/fckeditor/fckeditor.php");
		$oFCKeditor = new FCKeditor('MATCH_WIN_BODY') ;
		$oFCKeditor->BasePath	= ROOT_PATH.'/fckeditor/' ;
		$oFCKeditor->Value		= $configArray['MATCH_WIN_BODY'];
		$oFCKeditor->Height=400;
		$oFCKeditor->Width="98%";
		
		$oFCKeditor2 = new FCKeditor('MATCH_FAILURE_BODY') ;
		$oFCKeditor2->BasePath	= ROOT_PATH.'/fckeditor/' ;
		$oFCKeditor2->Value		= $configArray['MATCH_FAILURE_BODY'];
		$oFCKeditor2->Height=400;
		$oFCKeditor2->Width="98%";
		$this->view->assign('oFCKeditor',$oFCKeditor);
		$this->view->assign('oFCKeditor2',$oFCKeditor2);
    }
}